#include "universalquerymodel.h"
#include <QApplication>

UniversalQueryModel::UniversalQueryModel(QObject *parent)
        : QSqlQueryModel(parent)
{
    sfilter = "";
    selectionModel = 0;
    sortOrder = Qt::DescendingOrder;
    sortColumn = 0;
}

void UniversalQueryModel::setFilter(const QString &filter)
{
    sfilter = filter;
    refresh();
}

QString UniversalQueryModel::filter()
{
    return sfilter;
}

void UniversalQueryModel::refresh()
{

}

void UniversalQueryModel::setSelectionModel(QItemSelectionModel *selModel)
{
    selectionModel = selModel;
}

void UniversalQueryModel::saveSelState()
{
    selRowIds.clear();
    if(selectionModel) {
        QModelIndexList selState = selectionModel->selectedRows();
        for (int i = 0; i < selState.count(); ++i){
            selRowIds.append(QSqlQueryModel::data(QSqlQueryModel::index(selState.at(i).row(),0)).toInt());
        }
    }
}

void UniversalQueryModel::returnSelState()
{
    if (selectionModel){
        for (int i = 0; i < rowCount(); ++i) {
            int rowId = QSqlQueryModel::data(QSqlQueryModel::index(i,0)).toInt();
            foreach(int j, selRowIds) {
                if (rowId ==j) {
                    QModelIndex topLeft = QSqlQueryModel::index(i, 0, QModelIndex());
                    QModelIndex bottomRight = QSqlQueryModel::index(i, columnCount() - 1, QModelIndex());
                    QItemSelection selection(topLeft,bottomRight);
                    selectionModel->select(selection, QItemSelectionModel::Select);
                }
            }
        }
    }
    selRowIds.clear();
}


void UniversalQueryModel::selectRow(int rowId)
{
    if (!selectionModel)
        return;
    for (int i = 0; i < rowCount(); ++i) {
        if (QSqlQueryModel::data(QSqlQueryModel::index(i, 0)).toInt() == rowId) {
            selectionModel->clear();
            QModelIndex topLeft = QSqlQueryModel::index(i, 0, QModelIndex());
            QModelIndex bottomRight = QSqlQueryModel::index(i, columnCount() - 1, QModelIndex());
            QItemSelection selection(topLeft, bottomRight);
            selectionModel->select(selection, QItemSelectionModel::Select);
        }
    }
}

void UniversalQueryModel::sort(int /*column*/, Qt::SortOrder /*order*/)
{
}

void UniversalQueryModel::setSort(int column, Qt::SortOrder order)
{
    sort(column, order);
}


